import Mock from 'mockjs'
const baseURL = 'http://localhost:8080'
// 设置随机
// const Random = Mock.Random
// 设置全局延时，没有延时的话，有时候检测不到数据变化
Mock.setup({
  timeout: '300-600'
})

Mock.mock(RegExp(baseURL + '/login' + '.*'), 'get', options => {
  console.log(options, 'options')
  console.log(options.url.substr(options.url.indexOf('?') + 1).split('&'))
  const { username, password } = getCs(options)
  console.log(username, password)
  if (username === 'admin' && password === '123456') {
    return Mock.mock({
      data: {
        token: '@string("lower", 25)',
        status: 200,
        username: username
      }
    })
  } else {
    return Mock.mock({
      data: {
        status: 400
      }
    })
  }
})

function getCs(options) {
  var obj = {}
  console.log(options, 'ops')
  options.url
    .substr(options.url.indexOf('?') + 1)
    .split('&')
    .forEach(item => {
      console.log(item)
      item.split('=').forEach(v => {
        obj[item.split('=')[0]] = item.split('=')[1]
      })
    })
  // console.log(obj)
  return obj
}

// Mock.mock(baseURL + '/login', 'post', options => {
//   //   console.log(options)
//   console.log(JSON.parse(options.body))
//   const { username, password } = JSON.parse(options.body)
//   if (username === 'admin' && password === '123456') {
//     return Mock.mock({
//       data: {
//         token: '@string("lower", 25)',
//         status: 200,
//         username: username
//       }
//     })
//   } else {
//     return Mock.mock({
//       data: {
//         status: 400
//       }
//     })
//   }
// })

Mock.mock(baseURL + '/index/information', 'get', function() {
  return {
    data: [
      {
        title: '首页',
        level: 1,
        children: [
          {
            title: '系统首页',
            level: 2,
            path: 'windowIndex',
            children: [
              {
                title: '系统设置',
                path: 'system-setup'
              },
              {
                title: '账户设置',
                path: 'account-setting'
              },
              {
                title: '系统信息',
                path: 'system-info'
              },
              {
                title: '登陆日志',
                path: 'login-info'
              }
            ]
          }
        ]
      },
      {
        title: '商品',
        level: 1,
        children: [
          {
            title: '商品管理',
            level: 2,
            path: 'goodsManage',
            children: [
              {
                title: '商品列表',
                path: 'goods-list'
              },
              {
                title: '添加商品',
                path: 'add-goods'
              },
              {
                title: '商品审核',
                path: 'goods-audit'
              },
              {
                title: '商品回收站',
                path: 'goods-bin'
              },
              {
                title: '商品评价',
                path: 'goods-comment'
              }
            ]
          },
          {
            title: '商品配置',
            level: 2,
            path: 'goodspz',
            children: [
              {
                title: '商品分类',
                path: 'goods-cate'
              },
              {
                title: '规格参数',
                path: 'specification'
              },
              {
                title: '品牌管理',
                path: 'management'
              },
              {
                title: '图片库管理',
                path: 'photo-library'
              }
            ]
          }
        ]
      },
      {
        title: '订单',
        level: 1,
        children: [
          {
            title: '订单管理',
            level: 2,
            path: 'orderManage',
            children: [
              {
                title: '订单列表',
                path: 'order-list'
              },
              {
                title: '确认收货',
                path: 'confirm-receipt'
              },
              {
                title: '到货提醒',
                path: 'remind'
              },
              {
                title: '订单设置',
                path: 'order-settings'
              }
            ]
          },
          {
            title: '退货及退款',
            level: 2,
            path: 'tuihuanhuo',
            children: [
              {
                title: '退货申请处理',
                path: 'sales-return'
              },
              {
                title: '退款申请处理',
                path: 'refund'
              },
              {
                title: '退货原因设置',
                path: 'cause'
              }
            ]
          }
        ]
      },
      {
        title: '库存',
        level: 1,
        children: [
          {
            title: '库存记录',
            level: 2,
            path: 'repertyLog',
            children: [
              {
                title: '商品入库',
                path: 'storage'
              },
              {
                title: '商品出库',
                path: 'output'
              }
            ]
          }
        ]
      },
      {
        title: '用户',
        level: 1,
        children: [
          {
            title: '用户管理',
            level: 2,
            path: 'user-manage',
            children: [
              {
                title: '用户列表',
                path: 'user-list'
              },
              {
                title: '会员等级设置',
                path: 'vip-settings'
              }
            ]
          },
          {
            title: '成长值及橙币',
            level: 2,
            path: 'czbjcb',
            children: [
              {
                title: '成长值橙币查询',
                path: 'gup-search'
              },
              {
                title: '成长值及橙币设置',
                path: 'gup-settings'
              }
            ]
          }
        ]
      },
      {
        title: '运营',
        level: 1,

        children: [
          {
            title: '秒杀专区',
            level: 2,
            path: 'mszq',
            children: [
              {
                title: '秒杀活动列表',
                path: 'seckill-list'
              },
              {
                title: '时间段列表',
                path: 'time-list'
              }
            ]
          },
          {
            title: '满减专区',
            level: 2,
            path: 'mjzq',
            children: [
              {
                title: '满减活动列表',
                path: 'reduction-list'
              },
              {
                title: '添加满减活动',
                path: 'add-reduction'
              }
            ]
          },
          {
            title: '优惠劵管理',
            level: 2,
            path: 'yhjgl',
            children: [
              {
                title: '优惠劵列表',
                path: 'coupon-list'
              },
              {
                title: '添加优惠劵',
                path: 'add-coupon'
              },
              {
                title: '优惠劵查询',
                path: 'coupon-search'
              }
            ]
          },
          {
            title: '活动管理',
            level: 2,
            path: 'hdgl',
            children: [
              {
                title: '活动列表',
                path: 'activity-list'
              },
              {
                title: '添加活动',
                path: 'add-activity'
              }
            ]
          },
          {
            title: '广告管理',
            level: 2,
            path: 'gggl',
            children: [
              {
                title: '广告列表',
                path: 'ad-list'
              },
              {
                title: '添加广告',
                path: 'add-AD'
              }
            ]
          }
        ]
      },
      {
        title: '统计',
        level: 1,
        children: [
          {
            title: '统计分析',
            level: 2,
            path: 'tjfx',
            children: [
              {
                title: '交易统计',
                path: 'trade-statistic'
              },
              {
                title: '流量统计',
                path: 'flow-statistic'
              },
              {
                title: '商品统计',
                path: 'good-statistic'
              },
              {
                title: '会员统计',
                path: 'vip-statistic'
              },
              {
                title: '搜索统计',
                path: 'search-statistic'
              }
            ]
          }
        ]
      },
      {
        title: '财务',
        level: 1,
        children: [
          {
            title: '财务报表',
            level: 2,
            path: 'cwbb',
            children: [
              {
                title: '综合统计',
                path: 'syn-statistic'
              },
              {
                title: '销售统计',
                path: 'sell-statistic'
              }
            ]
          },
          {
            title: '对账管理',
            level: 2,
            path: 'dzgl',
            children: [
              {
                title: '对账列表',
                path: 'check-list'
              }
            ]
          }
        ]
      },
      {
        title: '设置',
        level: 1,
        path: 'set',
        children: [
          {
            title: '平台设置',
            level: 2,
            path: 'ptsz',
            children: [
              {
                title: '平台设置',
                path: 'terrace'
              },
              {
                title: '基本设置',
                path: 'base-settings'
              },
              {
                title: '消息提醒',
                path: 'msg'
              },
              {
                title: '验证码设置',
                path: 'verify-settings'
              }
            ]
          },
          {
            title: '支付配送',
            level: 2,
            path: 'zfps',
            children: [
              {
                title: '运费模板',
                path: 'fre-template'
              },
              {
                title: '物流公司',
                path: 'log-company'
              },
              {
                title: '支付设置',
                path: 'pay-settings'
              },
              {
                title: '区域管理',
                path: 'area-manage'
              }
            ]
          },
          {
            title: '权限管理',
            level: 2,
            path: 'qxgl',
            children: [
              {
                title: '角色管理',
                path: 'role-manage'
              },
              {
                title: '成员管理',
                path: 'member-manage'
              },
              {
                title: '操作日志',
                path: 'operate-log'
              },
              {
                title: '数据库管理',
                path: 'sql-manage'
              }
            ]
          }
        ]
      }
    ]
  }
})

Mock.mock(baseURL + '/ActiveController/findPage', 'post', options => {
  // if (!localStorage.getItem('ms-list')) {
  //   window.localStorage.setItem('userlist', JSON.stringify(mocklist))
  // }
  var msList = JSON.parse(localStorage.getItem('ms-list'))

  if (!msList) {
    const { pagesize, currentPage, queryString } = JSON.parse(
      options.body
    ).pagination
    console.log(pagesize, currentPage, queryString)
    if (!queryString) {
      var mock = Mock.mock({
        'data|100': [
          {
            'id|+1': 1000000,
            activeTitle: '@ctitle(6)',
            'startTime|+1': ['活动进行中', '活动已完成'],
            startTime: '@date',
            endTime: '@date',
            'status|0-1': 1
          }
        ],
        Flag: true
      })
      console.log(mock)
      mock['total'] = mock.data.length
      console.log(mock, '更新后')
      window.localStorage.setItem('ms-list', JSON.stringify(mock))
      return mock
    }
  } else {
    const { pagesize, currentPage, queryString } = JSON.parse(
      options.body
    ).pagination
    if (!queryString) {
      console.log(msList, 'mslist')
      console.log(pagesize, currentPage, queryString)
      let num1 = pagesize * currentPage - pagesize
      // console.log(pagesize * currentPage)
      // console.log(num1, 'dasdasdas')
      let temp = msList.data.slice(num1, num1 + pagesize)
      // console.log({ data: temp, Flag: true })
      return {
        data: temp,
        Flag: true,
        // 自加
        total: msList.data.length
      }
    } else {
      console.log(msList.length, 'mslitlength')

      let num1 = pagesize * currentPage - pagesize
      // console.log(pagesize * currentPage)
      // console.log(num1, 'dasdasdas')
      var temp = []
      msList.data.forEach(item => {
        if (item.activeTitle.includes(queryString)) {
          temp.push(item)
        }
      })
      console.log(msList.data.slice(num1, num1 + pagesize), '不等于0')
      let temp1 = temp.slice(num1, num1 + pagesize)
      // console.log({ data: temp, Flag: true })
      return {
        data: temp1,
        Flag: true,
        // 自加
        total: temp.length
      }
    }
  }

  // let { pagesize } = getCs(options)
  // pagesize = parseInt(pagesize)
  // console.log(pagesize)
  // if (pagesize === 0) {
  //   return Mock.mock({
  //     'data|16': [
  //       {
  //         'id|+1': 1000000,
  //         title: '@ctitle(6)',
  //         'status|+1': ['活动进行中', '活动已完成'],
  //         stime: '@date',
  //         etime: '@date',
  //         'boolean|1-2': true
  //       }
  //     ],
  //     status: 200,
  //     pagesize: 16,
  //     total: 100
  //   })
  // } else {
  //   return Mock.mock({
  //     [`data|${pagesize}`]: [
  //       {
  //         'id|+1': 1000000,
  //         title: '@ctitle(6)',
  //         'status|+1': ['活动进行中', '活动已完成'],
  //         stime: '@date',
  //         etime: '@date',
  //         'boolean|1-2': true
  //       }
  //     ],
  //     status: 200,
  //     total: 100,
  //     pagesize: pagesize
  //   })
  // }
})

// 上下架秒杀活动
Mock.mock(
  RegExp(baseURL + '/ActiveController/updateStatus' + '.*'),
  'get',
  options => {
    var msList = JSON.parse(window.localStorage.getItem('ms-list'))
    const { status, id } = getCs(options)
    console.log(status, id, 'sid')
    msList.data.forEach(item => {
      // console.log(item, 'item./.....')
      if (item.id === parseInt(id)) {
        console.log(item, 'item......')
        item.status = parseInt(status)
      }
    })
    window.localStorage.setItem('ms-list', JSON.stringify(msList))
    return { data: null, Flag: true }
  }
)

Mock.mock(baseURL + '/getTimeList', 'get', function() {
  return Mock.mock({
    data: [
      {
        id: 1000000,
        title: '8:00:00',
        stime: '08:00:00',
        etime: '10:00:00',
        'boolean|1-2': true
      },
      {
        id: 1000001,
        title: '12:00',
        stime: '10:00:01',
        etime: '12:00:00',
        'boolean|1-2': true
      },
      {
        id: 1000002,
        title: '14:00',
        stime: '12:00:01',
        etime: '14:00:00',
        'boolean|1-2': true
      },
      {
        id: 1000003,
        title: '16:00',
        stime: '14:00:01',
        etime: '16:00:00',
        'boolean|1-2': true
      },
      {
        id: 1000004,
        title: '18:00',
        stime: '16:00:01',
        etime: '18:00:00',
        'boolean|1-2': true
      },
      {
        id: 1000005,
        title: '20:00',
        stime: '18:00:01',
        etime: '20:00:00',
        'boolean|1-2': true
      },
      {
        id: 1000006,
        title: '22:00',
        stime: '20:00:01',
        etime: '22:00:00',
        'boolean|1-2': true
      }
    ],
    status: 200
  })
})

// 添加活动
Mock.mock(
  RegExp(baseURL + '/ActiveController/addActive' + '.*'),
  'get',
  options => {
    var obj1 = {}
    // console.log(options, '添加活动')
    let getHd = getCs(options)
    let msList = JSON.parse(window.localStorage.getItem('ms-list'))
    console.log(msList, 'dsadas')
    // console.log(msList.data[msList.data.length - 1].id, 'data')
    obj1 = {
      id: msList.data[msList.data.length - 1].id + 1,
      ...getHd
    }
    msList.data.push(obj1)
    window.localStorage.setItem('ms-list', JSON.stringify(msList))
    return { status: 200 }
  }
)

// 删除活动
Mock.mock(
  RegExp(baseURL + '/ActiveController/DeleteById' + '.*'),
  'get',
  options => {
    let msList = JSON.parse(window.localStorage.getItem('ms-list'))
    let { id } = getCs(options)
    console.log(parseInt(id), 'parseInt')
    let arr = msList.data.filter(item => item.id !== parseInt(id))
    window.localStorage.setItem(
      'ms-list',
      JSON.stringify({ data: arr, Flag: true, total: arr.length })
    )
    return {
      Result: {
        Data: null,
        Flag: true
      }
    }
  }
)

// 接收秒杀列表id  返回时间列表参数
Mock.mock(
  RegExp(baseURL + '/ActiveController/findGoodsCount' + '.*'),
  'get',
  options => {
    let { activeId } = getCs(options)
    // console.log(parseInt(activeId))
    return Mock.mock({
      data: [
        {
          id: parseInt(activeId),
          timeName: '8:00',
          startTime: '10:00:00',
          endTime: '11:00:00',
          count: '10'
        }
      ],
      Flag: true
    })
  }
)

// 单个时间段该活动对应的商品列表
Mock.mock(
  RegExp(baseURL + '/ActiveController/findGoods' + '.*'),
  'get',
  options => {
    let { activeId } = getCs(options)
    return Mock.mock({
      'data|10': [
        {
          id: parseInt(activeId),
          goodsName: 'iphoneXsMax128GB',
          goodsCode: 'No999999',
          price: 9999.0,
          allowPrice: 8000.0,
          count: 100,
          remainCount: 50
        }
      ],
      Flag: true
    })
  }
)

// 查询分页
Mock.mock(
  RegExp(baseURL + '/ActiveController/findaddGoodsBack' + '.*'),
  'post',
  options => {
    console.log(options.body)
    const { currentPage, queryString } = JSON.parse(options.body).pagination
    console.log(currentPage, queryString, '已拿到值')
  }
)

// 编辑 (自加接口)
Mock.mock(baseURL + '/ActiveController/editActive', 'post', options => {
  console.log(options.body, 'bodyddddd')
  const { id, name, startTime, endTime, radio } = JSON.parse(
    options.body
  ).params
  let msList = JSON.parse(window.localStorage.getItem('ms-list'))
  console.log(id, 'id.///////')
  console.log(msList.data)
  const index = msList.data.findIndex(item => {
    return item.id === id
  })
  // console.log(index, 'index')
  msList.data[index] = {
    id: id,
    activeTitle: name,
    startTime: startTime,
    endTime: endTime,
    status: radio
  }
  console.log(msList, '修改后的数据')
  window.localStorage.setItem('ms-list', JSON.stringify(msList))
  return { Flag: true }
})

Mock.mock(baseURL + '/commodity/findPage', 'post', options => {
  console.log(options, 'options')
  let { currentPage } = JSON.parse(options.body).pagination
  console.log(currentPage, 'number')
  return Mock.mock({
    'data|10': [
      {
        'id|+1': 1000000,
        categoryName: '@ctitle(2)',
        'commodityNum|1-100': 1,
        'navigationBar|0-1': 1,
        'is_show|0-1': 1,
        sqe: 1
      }
    ],
    Flag: true
  })
})

// get请求
Mock.mock(baseURL + '/commodity/findSuperior', 'get', function() {
  return Mock.mock({
    data: [
      {
        id: 50,
        categoryName: '服装',
        parent_id: 0,
        findSuperior: [
          {
            id: 65,
            categoryName: '外套',
            parent_id: 50,
            findSuperior: [
              {
                id: 95,
                categoryName: '牛仔衣',
                parent_id: 65
              }
            ]
          }
        ]
      },
      {
        id: 51,
        categoryName: '通讯',
        parent_id: 0,
        findSuperior: [
          {
            id: 66,
            categoryName: '手机',
            parent_id: 51,
            findSuperior: [
              {
                id: 96,
                categoryName: '苹果手机',
                parent_id: 66
              }
            ]
          }
        ]
      },
      {
        id: 52,
        categoryName: '电子设备',
        parent_id: 0,
        findSuperior: [
          {
            id: 67,
            categoryName: '电脑外设',
            parent_id: 52,
            findSuperior: [
              {
                id: 97,
                categoryName: '键盘',
                parent_id: 67
              }
            ]
          }
        ]
      },
      {
        id: 53,
        categoryName: '汉服',
        parent_id: 0
      }
    ],
    Flag: true
  })
})

Mock.mock(baseURL + '/commodity/findTemlate', 'get', function() {
  return Mock.mock({
    data: [
      { id: 5, template_name: '手机' },
      { id: 6, template_name: '服装' }
    ],
    Flag: true
  })
})

// post请求 新增分类
Mock.mock(baseURL + '/commodity/addCommodity', 'post', options => {
  console.log(JSON.parse(options.body), 'post新增分类')
  return Mock.mock({
    Flag: true
  })
})

// 删除下级
Mock.mock(
  RegExp(baseURL + '/commodity/deleteCommodity' + '.*'),
  'get',
  options => {
    // console.log(, 'optisssss')
    console.log(getCs(options))
    const { id } = getCs(options)
    console.log(id)
    return Mock.mock({
      Flag: true
    })
  }
)
// // 创建一个数组用来接收模拟的数据
// const mocklist = []

// mocklist.push(
//   (function getComments() {
//     const data = Mock.mock({
//       'message|20': [
//         {
//           'userid|+1': 1,
//           username: '@name()',
//           creat_time: '@datetime()',
//           content: '@csentence(10,12)'
//         }
//       ]
//     })
//     return data
//   })()
// )
// console.log(mocklist)

// // 获取评论列表信息
// function getList() {
//   if (!localStorage.getItem('userlist')) {
//     window.localStorage.setItem('userlist', JSON.stringify(mocklist))
//   }
//   var userlist = JSON.parse(window.localStorage.getItem('userlist'))
//   return userlist
// }

// // 添加评论列表
// function addPl(optons) {
//   var userlist = JSON.parse(window.localStorage.getItem('userlist'))
//   var user = JSON.parse(optons.body)
//   //   使用mock随机生成id
//   user.id = Random.id()
//   console.log(user, 'user')
//   console.log(userlist, 'usedrlits')
//   // 将user插入userlist中
//   userlist[0].message.unshift(user)
//   //   重新存储
//   localStorage.setItem('userlist', JSON.stringify(userlist))
//   return {
//     status: 1,
//     data: '用户添加成功'
//   }
// }

// Mock.mock('/api/comment', 'get', getList)
// Mock.mock('/api/add/comment', 'post', addPl)
